package com.me.app;

import java.util.ArrayList;

import com.me.db.CalendarManager;
import com.me.db.CalendarQuery;
import com.me.util.AppConstant;
import com.me.util.AppUtil;

import android.app.ActionBar;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.view.MenuItem;

public class SettingsActivity extends PreferenceActivity {

	CalendarManager calendarManager;
	static SharedPreferences sharedPref;
	static CharSequence[] accounts;
	static CharSequence[] ids;

	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

		// Set up the action bar.
		final ActionBar actionBar = getActionBar();
		actionBar.setDisplayHomeAsUpEnabled(true);

	    getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit();
	    
		calendarManager = new CalendarManager(getContentResolver());

		// query the android calendar
		Cursor cursor = calendarManager.fetchCalendar();
		int count = cursor.getCount();

		if (count > 0) {
			ArrayList<String> accountList = new ArrayList<String>();
			ArrayList<String> idList = new ArrayList<String>();

			// retrieve the result from cursor
			while (cursor.moveToNext()) {
				accountList.add(cursor.getString(CalendarQuery.Calendar.INDEX_ACCOUNT_NAME));
				idList.add(String.valueOf(cursor.getInt(CalendarQuery.Calendar.INDEX_ID)));
			}
			
			accounts = accountList.toArray(new CharSequence[accountList.size()]);
			ids = idList.toArray(new CharSequence[idList.size()]);
		}
		
		
		sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    }

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == android.R.id.home) {
			onBackPressed();
		}
		return super.onOptionsItemSelected(item);
	}
	

    /**
     * This fragment shows the preferences for the first header.
     */
    public static class SettingsFragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            // Load the preferences from an XML resource
            addPreferencesFromResource(R.xml.preferences);
            
            
            // Setting Google Account
            final ListPreference account_preference = (ListPreference) this.findPreference("account_preference");
			account_preference.setEntries(accounts);
			account_preference.setEntryValues(ids);
			
			if (account_preference.getValue() == null) {
	            account_preference.setValue(AppUtil.App.currCalendarId);
			}
			account_preference.setTitle(AppUtil.App.currCalendarName);
            
            account_preference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
				@Override
				public boolean onPreferenceChange(Preference preference, Object newValue) {
					// Set the value as the new value
					account_preference.setValue(newValue.toString());
					// Get the entry which corresponds to the current value and set as title
					account_preference.setTitle(account_preference.getEntry());
					
					AppUtil.App.currCalendarId = newValue.toString();
					AppUtil.App.currCalendarName = account_preference.getEntry().toString();
					
					// save the retrieved calendar id and calendar name
					SharedPreferences.Editor editor = sharedPref.edit();
					editor.putString(AppConstant.CURRENT_CALENDAR_ID,
							AppUtil.App.currCalendarId);
					editor.putString(AppConstant.CURRENT_CALENDAR_NAME,
							AppUtil.App.currCalendarName);
					editor.commit();
					
					AppUtil.Event.settingChanged = true;
					return true;
				}          	
            });
			       
            
            // Setting Floating Button Size: Small, Medium, Large
            final ListPreference button_size_preference = (ListPreference) this.findPreference("button_size_preference");
			if (button_size_preference.getValue() == null) {
				button_size_preference.setValue(AppUtil.App.currButtonSize);
			}
            button_size_preference.setSummary(AppUtil.App.currButtonSize);

			button_size_preference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
				@Override
				public boolean onPreferenceChange(Preference preference, Object newValue) {
					
					AppUtil.App.currButtonSize = newValue.toString();
					
					button_size_preference.setValue(newValue.toString());
					button_size_preference.setSummary(newValue.toString());
														
					// save preference
					SharedPreferences.Editor editor = sharedPref.edit();
					editor.putString(AppConstant.CURRENT_BUTTON_SIZE, newValue.toString());
					editor.commit();
					
					AppUtil.Event.settingChanged = true;
					return true;
				}          	
            });
            
            // Setting Default Homepage
            final ListPreference homepage_preference = (ListPreference) this.findPreference("homepage_preference");
            
			if (homepage_preference.getValue() == null) {
				homepage_preference.setValue(AppUtil.App.defaultEventType);
			}
			homepage_preference.setSummary(AppUtil.App.defaultEventType);

            homepage_preference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
				@Override
				public boolean onPreferenceChange(Preference preference, Object newValue) {
					
					AppUtil.App.defaultEventType = newValue.toString();

					homepage_preference.setValue(newValue.toString());
					homepage_preference.setSummary(newValue.toString());
					
					// save preference
					SharedPreferences.Editor editor = sharedPref.edit();
					editor.putString(AppConstant.DEFAULT_EVENT_TYPE, newValue.toString());
					editor.commit();
					
					AppUtil.Event.settingChanged = true;
					return true;
				}          	
            });
        }
    }
}